# ilms/lib/serial_interface.rb

class SerialInterface < ApplicationController
	def initialize
		begin 
			@portw = SerialPort.new('/dev/tty.usbserial-A900adFu', 9600, 8, 1, SerialPort::NONE)
			@portr = SerialPort.new('/dev/tty.usbserial-A900adFu', 9600, 8, 1, SerialPort::NONE)
		rescue Exception => e
			puts e.message
			puts 'Not connected to ILMS box'
		end
	end
	
	def send_outlet(data)
		for port in data
			@portw.print(port.chr)
		end
	end
	
	#def self.read_power
	#	if @portw == nil
	#		ilms = SerialInterface.new
	#		sleep 1
	#		ilms.read_power
	#	end
	#end
	
	def read_power
		# send request for measurements to Arduino
		
		@portw.print(9.chr)

		#9.times do
		#	inP = @portr.getc
		#	if inP.to_s.match(/\A[+-]?(\.\d+)?\Z/)==nil
		#		power << inP
		#	end
		#end
		# retrieve power
		p = @portr.gets
		p = p.chomp.to_i
		# retrieve current
		c = @portr.gets
		c = c.chomp.to_f
		# if the current looks like it is rediculously high, then the ilms box has
		# probably switched the two. so realignment is needed
		if c > 10
			p = @portr.gets
			return [c, p]
		else
		    # normal return functioning of the ilms power measurement
			return [p, c]
		end
	end
	
	def self.close
		@portr.close
		@portw.close
	end
	
end
